<template>
  <div class="chart-content-wrapper" @mouseenter="mouseenter()" @mouseleave="mouseleave">
    <top-filter :title="reportName" ref="topFilter">
      <double-check-filter :pageChange="pageChange" :isParentLinkChild="true" @confirmDoubleSelect="planAreaSelect" defaultText="统筹区"
                           :filter="filterN" type="planArea"></double-check-filter>
      <single-list-filter-without-cb :defaultText="'养老保险'" :filter="filterN" :type="'socialInsurance'"
                                     @confirmSingleSelect="confirmSingleSelectSiType"
                                     :leftTipText="'险种'"
                                     v-if="insuranceCode == 1000"
      ></single-list-filter-without-cb>
      <single-list-filter-without-cb :pageChange="pageChange" :filter="filterN" :type="'years'"
                                     @confirmSingleSelect="chooseYear" ref="yearsFilter">
      </single-list-filter-without-cb>
    </top-filter>
    <div class="chart-container" v-show="isShowChart">
      <div id="base-on-payment-people-analyse-id" class="chart-type1"></div>
      <div class="month-select-wrapper">
        <i class="move-arrow left-move-arrow icon-arrow-down" @click="leftClickArrow"></i>
        <i class="move-arrow right-move-arrow icon-arrow-down" @click="rightClickArrow"></i>
        <div class="social-fund-slider-bar-wrapper expand-slider-style-up">
          <el-slider
            v-model="value7"
            :step="getStep()"
            :show-tooltip="false"
            show-stops>
          </el-slider>
        </div>
        <div class="social-fund-slider-bar-wrapper expand-slider-style">
          <div class="el-slider__runway-bottom">
            <div v-for="(item,index) in step">
              <div class="el-slider__stop" :style="{left: getStep()*index+ '%'}">
                <div style="margin-top: 20px;margin-left: -20px;width: 50px"
                     :class="{'select-current-dot':index==position}" v-html="getQueryYearMonth(item)">
                  <!--{{getQueryYearMonth(item)}}-->
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <Summarize :showSummarizeText="conclusion"></Summarize>
    </div>
  </div>
</template>

<script>
  import {setChartHeight, seqencingArr, loadingOpt} from '../../../assets/js/utils.js'
  import SingleListFilter from '../../last/filter/single-list-filter.vue'
  import DoubleCheckFilter from '../../last/filter/double-check-filter.vue'
  import TopFilter from '../../last/filter/top-filter1.vue'
  import {getBasePaymentPeopleAnalyse} from "../../../api/last-api";
  import Summarize from '../../last/summarize/summarize.vue'
  import SingleListFilterWithoutCb from '../../last/filter/single-list-filter-without-checkbox'
  export default {
    name: 'chart2',
    props: ['isChange', 'filter', 'insuranceCode', 'insuranceText','pageChange'],
    components: {
      SingleListFilter,
      DoubleCheckFilter,
      TopFilter,
      Summarize,
      SingleListFilterWithoutCb
    },
    data () {
      return {
        filterN: JSON.parse(JSON.stringify(this.filter)),
        conclusion: '',
        areaCode: null,
        hospLevel: this.filter.nc.hospitalRankType[1].selectId,
        queryYear: '',
        json: {},
        reportName: '2018年区域医疗费用增长比较分析',
        insuredObj: {'insuredCode': '', 'insuredName': ''},
        isShowChart: true,
        height: 400,
        value7: 0,
        position: -100,
        step: 12
      }
    },
    created(){
      this.initInsuredObj();
    },
    mounted(){
      this.initInsuredObj();
      let areaCode = []
      let areaCodeText = []
      this.filter.nc.planArea.map((item, index) => {
        if (index > 0 && index <= 6) {
          areaCode.push(item.selectId)
          areaCodeText.push(item.selectName)
        }
      })
      this.areaCode = areaCode.join(',');
      this.areaCodeText = areaCodeText.join('、')
      // 设置默认月份
      this.queryYear = this.$refs.yearsFilter.getSingleListData()[0].selectName
      this.setCurrentYearAndMonth()
      setChartHeight();
      // 基于准备好的dom，初始化echarts实例
      this.myChart = this.$echarts.init(document.getElementById('base-on-payment-people-analyse-id'), null, {renderer: 'canvas'})
      this.getData();
      this.chartClick();
//      this.myChart.on('legendselectchanged', function (params) {
//        let option = this.getOption();
//        let select_key = Object.keys(params.selected);
//        if (!params.selected[params.name]) {
//          select_key.map(res => {
//            option.legend[0].selected[res] = true;
//          });
//        } else {
//          select_key.map(res => {
//            option.legend[0].selected[res] = true;
//          });
//          option.legend[0].selected[params.name] = true;
//        }
//        let legend = []
//        that.myChart.dispatchAction({
//          type: 'legendselectchanged',
//          batch: legend
//        });
//        that.myChart.setOption(option)
//      })
    },
    watch: {
      insuranceCode (val) {},
      pageChange(){
        let val = this.$route.params.id;
        let temtInsuredCode = 1001;
        if (val == 1000) {
          temtInsuredCode = 1001;
        } else {
          temtInsuredCode = val;
        }
        let areaCode = []
        let areaCodeText = []
        this.filter.nc.planArea.map((item, index) => {
          if (index > 0 && index <= 6) {
            areaCode.push(item.selectId)
            areaCodeText.push(item.selectName)
          }
        })
        this.areaCode = areaCode.join(',');
        this.areaCodeText = areaCodeText.join('、')
        // 设置默认月份
        this.queryYear = this.$refs.yearsFilter.getSingleListData()[0].selectName
        this.setCurrentYearAndMonth()
        this.insuredObj.insuredCode = temtInsuredCode;
        this.insuredObj.insuredName = this.insuranceText;
        this.myChart = this.$echarts.init(document.getElementById('base-on-payment-people-analyse-id'), null, {renderer: 'canvas'})
        this.getData();
        this.chartClick();
      },
      isChange(){
        setTimeout(() => {
          setChartHeight();
          setTimeout(() => {
            this.myChart.resize();
          }, 10)
        }, 101)
      },
      value7(newVal){
        if (newVal >= 0) {
          this.position = Math.round(newVal / this.getStep());
        }
      },
      position(newVal) {
        if (newVal >= 0) {
          this.getData()
        }
      }
    },
    methods: {
      chartClick(){
        let that = this;
        let hash = window.location.hash;
        this.myChart.off('click')
        this.myChart.on('click', (item) => {
          if (item.componentSubType === 'pie') {
            this.mouseleave()
            let dataIndex = item.dataIndex;
            let startDateTem = this.position + 1;
            let month = startDateTem < 10 ? '0' + startDateTem : '' + startDateTem
            // 转换传参的index
            let dataIndexRadio;
            if (dataIndex == 0) {
              dataIndexRadio = 0
            } else if (dataIndex == 1) {
              dataIndexRadio = 2
            } else if (dataIndex == 2) {
              dataIndexRadio = 1
            }
            let dataJson = {
              'areaName': this.areaCodeText,
              'areaCode': this.areaCode,
              'insuredName': this.insuredObj.insuredName,
              'insuredCode': this.insuredObj.insuredCode,
              'year': this.queryYear,
              'month': month,
              'explain': `缴费基数为社平工资${this.json.jiShuRate[dataIndex]}的人数`,
              'explainCode': dataIndexRadio,
              'hash': hash,
            };

            this.$router.push({path: `/application/base-on-payment-people-analyse-detail`, query: dataJson})
          }
        });
      },
      setCurrentYearAndMonth() {
        let myDate = new Date();
        let curYear = myDate.getFullYear();
        let curMonth = myDate.getMonth() + 1;
        if (this.queryYear == curYear) {
          // 设置为为上一个月
          this.position = curMonth - 2
          this.step = this.position + 1
        } else {
          this.position = 11
          this.step = this.position + 1
        }
        this.value7 = this.getStep() * this.position
      },
      leftClickArrow() {
        this.value7 -= this.getStep()
        this.position -= 1;
        if (this.position < 0) {
          this.position = 0
        }
      },
      rightClickArrow(){
        this.value7 += this.getStep()
        this.position += 1;
        if (this.position > this.step - 1) {
          this.position = this.step - 1
        }
      },
      getQueryYearMonth(startDateTem) {
//        let month = startDateTem < 10 ? '-0' + startDateTem : '-' + startDateTem
//        return this.queryYear + month
        let month = startDateTem < 10 ? '0' + startDateTem : '' + startDateTem
        return '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' + month
      },
      getStep() {
        return 100 / (this.step - 1);
      },
      initInsuredObj () {
        if (this.filter.nc.insuranceTypes.length > 0) {
          let item = this.filter.nc.insuranceTypes[0];
          this.insuredObj.insuredCode = item.selectId;
          this.insuredObj.insuredName = item.selectName;
        }
      },
      // 险种点击
      confirmSingleSelectSiType (selectedId, selectedName) {
        this.insuredObj.insuredCode = selectedId;
        this.insuredObj.insuredName = selectedName;
        this.getData();
      },
      mouseenter(){
        this.$refs.topFilter._hideChartTitle()
      },
      mouseleave() {
        this.$refs.topFilter._showChartTitle()
      },
      getData(){
        setChartHeight();
        if (this.myChart) {
          this.myChart.clear();
          this.myChart.showLoading(loadingOpt)
        }
        let startDateTem = this.position + 1;
        let month = startDateTem < 10 ? '0' + startDateTem : '' + startDateTem
        getBasePaymentPeopleAnalyse(this.areaCode, this.insuredObj.insuredCode, this.queryYear + month).then(response => {
          this.json = response.data;
          if (response.code === 0) {
            this.isShowChart = true;
            this.myChart.hideLoading();
            this.reportName = this.json.reportName;
            this.conclusion = this.json.conclusion;
            this.myChart.resize();
            this.drawLine(this.json)
          } else {
            this.isShowChart = false;
          }
        }).catch(res => {
//          console.log(res)
          this.isShowChart = false;
        })
      },
      avg(arry){
        let sum = 0;
        let len = arry.length;
        for (let i = 0; i < len; i++) {
          sum += arry[i];
        }
        let d = parseInt((sum / len) * 100) / 100;
        return d;
      },
      chooseYear(year){
        this.queryYear = year;
        this.setCurrentYearAndMonth()
        this.getData();
        //选择年份后执行事件
      },
      planAreaSelect(filter, chooseListName){
        //统筹区选择
        this.areaCodeText = chooseListName.join('、')
        this.areaCode = filter.join(',')
        this.getData();
      },
      hospLevelSelect(filter){
        //医院级别选择
        this.hospLevel = filter.join(',');
        this.getData();
      },
      drawLine(json){
        let colorList = ['#3281FD', '#FF6A93', '#FFD66A'];
        let legendData = []
        json.renShuXianShi.forEach((item, dataIndex) => {
          legendData.push({
            name: `{c|}{a|缴费基数为社平工资${json.jiShuRate[dataIndex]}的人数}\n{d|}{a|}{b|${item}}{a|${json.renShuXianShiDanWei[dataIndex]}}`,
            value: json.zhanBi[dataIndex],
            textStyle: {
              rich: {
                a: {
                  color: '#ffffff',
                  lineHeight: 30,
                  verticalAlign: 'bottom',
                  padding: [0, 0, 0, 10],
                },
                b: {
                  color: colorList[dataIndex],
                  lineHeight: 30,
                  fontSize: 20,
                  verticalAlign: 'bottom'
                },
                c: {
                  backgroundColor: colorList[dataIndex],
                  width: 10,
                  height: 10,
                  verticalAlign: 'bottom',
                  lineHeight: 30,
                },
                d: {
                  backgroundColor: 'rgba(0,0,0,0)',
                  width: 10,
                  height: 10,
                  verticalAlign: 'bottom',
                  lineHeight: 30,
                }
              }
            }
          })
        })
        // 绘制图表
        this.myChart.setOption(
          {
            tooltip: {
              show: true,
              textStyle: {
                fontSize: 12
              },
              formatter: function (params) {
//                console.log(params)
                let dataIndex = params.dataIndex;
                return `<span style="color: #fff">缴费基数为社平工资${json.jiShuRate[dataIndex]}的人数</span></br>
                      <span style="color: #fff">人数: ${json.renShuXianShi[dataIndex]}${json.renShuXianShiDanWei[dataIndex]}</span></br>
                      <span style="color: #fff">占比: ${json.zhanBi[dataIndex]}%</span></br>
                      <span style="color: #fff">社平工资${json.jiShuRate[dataIndex]}: ${json.jiShu[dataIndex]}元</span></br>
                      <span style="color: #67ffdb;
                            text-align: center;
                            line-height: 30px;height: 30px">点击图表查看人员画像</span>`;
              },
            },
            legend: [
              {
                orient: 'vertical',
                // x: 'left',
                top: '20%',
                left: '55%',
                selectedMode: false,
                textStyle: {
                  color: '#fff'
                },
                itemWidth: 10,
                itemHeight: 10,
                data: legendData,
              },
//              {
//                orient: 'vertical',
//                top: '40%',
//                left: '75%',
//                textStyle: {
//                  color: '#fff'
//                },
//                icon: 'rect',
//                itemWidth: 10,
//                itemHeight: 10,
//                selectedMode: false,
//                data: data.pieData.numDesc
//              }
            ],
            series: [
              {
                name: '基于性别的养老支出统计',
                type: 'pie',
                radius: ['30%', '50%'],
                center: ['30%', '45%'],
                clockwise: false,
                hoverAnimation: false,
                avoidLabelOverlap: false,
                minAngle: 5,
                label: {
                  show: true,
                  position: 'center',
                  formatter: function (params) {
                    if (params.dataIndex == 0) {
//                      return `<span style="color:#67FFDB">832.75</span><br><span style="color:#67FFDB">当月统计总人数</span>`
                      return `{a|${json.zongRenShu}}\n{b|当月统计总人数}\n{b|（${json.zongRenShuDanWei}）}`
                    } else {
                      return ''
                    }
                  },
                  rich: {
                    a: {
                      color: '#67FFDB',
                      lineHeight: 20,
                      fontSize: 16,
                      fontWeight: 700
                    },
                    b: {
                      color: '#67FFDB',
                      lineHeight: 20
                    }
                  }
                },
                itemStyle: {
                  color: function (params) {
                    return colorList[params.dataIndex]
                  }
                },
                data: legendData
              },
//              {
//                name: '基于性别的养老支出统计',
//                type: 'pie',
//                hoverAnimation: false,
//                radius: ['60%', '80%'],
//                clockwise: false,//是否按顺时针来排布 false为按逆时针排布。
//                label: {
//                  show: false,
//                },
//                itemStyle: {
//                  color: function (params) {
//                    let colorList = ['#3281fd', '#ff6a93', '#888', '#ccc'];
//                    return colorList[params.dataIndex]
//                  }
//                },
//                data: data1
//              }
            ]
          }
        )
      }
    }
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="scss">
  .month-select-wrapper {
    position: relative;
    bottom: 18%;
    left: 2.5%;
    width: 95%;

    .select-current-dot {
      color: #5BDEC1;
    }

    .move-arrow {

    }

    .left-move-arrow {
      position: absolute;
      left: -10px;
      height: 38px;
      line-height: 38px;
      color: #3281FD;
      font-size: 20px;
      transform: rotate(90deg);
    }
    .right-move-arrow {
      position: absolute;
      right: -10px;
      height: 38px;
      line-height: 38px;
      color: #3281FD;
      font-size: 20px;
      transform: rotate(-90deg);
    }
  }

  .social-fund-slider-bar-wrapper {
    position: absolute;
    z-index: 10;
    left: 2.5%;
    width: 95%;

    .el-slider__stop {
      position: absolute;
      height: 5px;
      width: 5px;
      top: -2.25px;
      border-radius: 50%;
      background-color: #1B2B44;
      border: 2px solid #53C8B4;
      -webkit-transform: translateX(-50%);
      transform: translateX(-50%);
    }

    .el-slider__button {
      width: 10px;
      height: 10px;
      border: 2px solid #53C8B4;
      margin-top: -2px;
      background-color: #3281FD;
      border-radius: 50%;
      -webkit-transition: .2s;
      transition: .2s;
      -webkit-user-select: none;
      -moz-user-select: none;
      -ms-user-select: none;
      user-select: none;
    }

    .el-slider__runway {
      width: 100%;
      height: 3px;
      margin: 16px 0;
      background-color: transparent;
      border-radius: 3px;
      position: relative;
      cursor: pointer;
      vertical-align: middle;
    }

    .el-slider__runway-bottom {
      width: 100%;
      height: 3px;
      margin: 16px 0;
      background-color: #3281FD;
      border-radius: 3px;
      position: relative;
      cursor: pointer;
      vertical-align: middle;
    }

    .el-slider__bar {
      height: 6px;
      background-color: #ffffff;
      border-top-left-radius: 3px;
      border-bottom-left-radius: 3px;
      position: absolute;
      display: none;
    }
  }

  .expand-slider-style {
    z-index: 9;
  }

  /*.expand-slider-style-up {*/
  /*background: transparent;*/
  /*}*/
  /*.el-slider {*/
  /*background: transparent;*/
  /*}*/
</style>
